package com.woniuxy.woniufp.sms.controller;

import cn.hutool.core.util.RandomUtil;
import com.woniuxy.woniufp.common.model.constant.RedisConstant;
import com.woniuxy.woniufp.common.model.result.Result;
import com.woniuxy.woniufp.sms.config.SmsTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Api("短信服务")
public class SmsController {
    @Autowired
    SmsTemplate smsTemplate ;

    @Autowired
    StringRedisTemplate stringRedisTemplate ;

    @GetMapping("/sms/sendCode")
    @ApiOperation("发送短信")
    public Result sendSms(String phone){
        //存储redis
        String redis_key = RedisConstant.REDIS_SMS_PREFIX + phone ;
        String code = stringRedisTemplate.opsForValue().get(redis_key);
        if (code == null) {
            //获取一个 随机验证码
            code = RandomUtil.randomNumbers(4);
        }
        smsTemplate.sendSms(phone,code);
        stringRedisTemplate.opsForValue().set(redis_key,code,5, TimeUnit.MINUTES);

        return Result.ok(code);
    }
}
